import traceback

from app.vecmdb import get_ci


def dict_handle(query_model, query_field, db_name, filter_data=None):
    if filter_data is None:
        filter_data = {}
    info = list(query_model.objects.using(db_name).filter(**filter_data).order_by(query_field).values(query_field).distinct().values_list(query_field, flat=True))
    data = []
    for item in info:
        data.append({"label": item, "value": item}) if item else None
    return data


def get_domain_account(request):
    """获取登录的域账号"""
    account = request.session.get('username')
    if not account:
        account = request.headers.get('authName', None)
    return account


def get_dict_value(dict_data):
    """获取字典中有值的key"""
    if not dict_data:
        return dict_data
    new_dict = {}
    for key, value in dict_data.items():
        if value:
            new_dict[key] = value
    return new_dict


def is_score_range(range_score, score):
    """判断分数是否在这范围, range_score: [0,60], [120,-]"""
    if not range_score:
        return False
    try:
        start_str, end_str = range_score.strip().replace('[', '').replace(']', '').split(',')

        start_str = start_str.strip()
        end_str = end_str.strip()
        start = float(int(start_str))

        if end_str in ['-', '--', '---', '']:
            return score >= start
        else:
            end = float(int(end_str))
            return start <= score <= end
    except Exception as e:
        print(traceback.print_exc())
        return False


def query_server(sn):
    """查询服务器"""
    payload = {
        "q": f"_type:PhysicalMachineResource,systemSN:{sn}",
        "count": 10,
        "page": 1,
    }
    res = get_ci(payload)
    if 'message' in res:
        return False, res.get('message')

    info = res.get('result')
    if not len(info):
        return False, 'empty'
    else:
        return True, 'success'


def is_float(value):
    if value:
        return float(value)
    else:
        return None

